package com.maoshi.shop.user.multishop.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maoshi.shop.bean.dto.OrderRefundDto;
import com.maoshi.shop.bean.enums.ScoreLogType;
import com.maoshi.shop.bean.event.OrderRefundSuccessEvent;
import com.maoshi.shop.bean.model.Order;
import com.maoshi.shop.bean.model.OrderItem;
import com.maoshi.shop.bean.model.UserExtension;
import com.maoshi.shop.service.OrderService;
import com.maoshi.shop.service.UserExtensionService;
import com.maoshi.shop.user.comment.model.UserScoreLog;
import com.maoshi.shop.user.comment.service.UserScoreLogService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 退款订单监听
 * @author lhd
 */
@Component("userOrderRefundListener")
@AllArgsConstructor
public class OrderRefundListener {

    private final UserExtensionService userExtensionService;
    private final UserScoreLogService userScoreLogService;
    private final OrderService orderService;


    /**
     * 退还用户此笔退款订单使用的积分
     */
    @EventListener(OrderRefundSuccessEvent.class)
    public void userOrderRefundSuccessEvent(OrderRefundSuccessEvent event) {
        OrderRefundDto orderRefundDto = event.getOrderRefundDto();
        //获取退款的所有订单项
        if (CollectionUtils.isEmpty(orderRefundDto.getOrderItems())) {
            return;
        }
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderRefundDto.getOrderNumber()));
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId,order.getUserId()));
        List<UserScoreLog> scoreLogs = new ArrayList<>();
        //退还用户此笔退款订单使用的积分,如果有确认收货还需扣减掉获取的积分。
        List<OrderItem> orderItems = orderRefundDto.getOrderItems();
        int totalScore = 0;
        int totalGainScore = 0;
        for (OrderItem orderItem : orderItems) {
            totalScore += orderItem.getUseScore();
            //确认收货时赠送的积分
            totalGainScore += orderItem.getGainScore() == null?0:orderItem.getGainScore();
        }
        if(totalScore > 0) {
            //添加积分日志
            UserScoreLog userScoreLog = new UserScoreLog();
            userScoreLog.setUserId(order.getUserId());
            userScoreLog.setScore(totalScore);
            userScoreLog.setBizId(order.getOrderId());
            userScoreLog.setSource(ScoreLogType.SCORE_CASH.value());
            userScoreLog.setCreateTime(new Date());
            userScoreLog.setIoType(1);
            scoreLogs.add(userScoreLog);
            userExtension.setScore(userExtension.getScore() + totalScore);
        }
        //确认收货后的退款,还需将用户完成此笔订单获取的积分扣除
        if(totalGainScore > 0){
            //添加积分日志
            UserScoreLog log = new UserScoreLog();
            log.setUserId(order.getUserId());
            log.setScore(totalGainScore);
            log.setBizId(order.getOrderId());
            log.setSource(ScoreLogType.SHOP.value());
            log.setCreateTime(new Date());
            log.setIoType(0);
            scoreLogs.add(log);
            userExtension.setScore(userExtension.getScore() - totalGainScore);
        }
        //如果不为空则批量保存积分日志
        if(CollectionUtils.isNotEmpty(scoreLogs)){
            userScoreLogService.saveBatch(scoreLogs);
        }
        userExtensionService.updateById(userExtension);
//                Product product = productService.getProductByProdId(orderItem.getProdId());
//                //获取历史扣除的积分
//                List<UserScoreLog> historyLogs = userScoreLogService.list( new LambdaQueryWrapper<UserScoreLog>()
//                                                    .eq(UserScoreLog::getSource,ScoreLogType.SHOP.value())
//                                                    .eq(UserScoreLog::getBizId, order.getOrderId())
//                                                    .eq(UserScoreLog::getIoType,0));
//                //获取可以扣除的积分
//                for (UserScoreLog historyLog : historyLogs) {
//                    receiptScore -= historyLog.getScore();
//                }
                //获取用户当前等级
//                UserLevel nowLevel = userLevelService.getOne(new LambdaQueryWrapper<UserLevel>()
//                        .eq(UserLevel::getLevel, userExtension.getLevel())
//                        .eq(UserLevel::getLevelType, userExtension.getLevelType()));
//                //获取配置信息
//                ScoreConfigParam scoreParam = sysConfigService.getSysConfigObject(Constant.SCORE_CONFIG,ScoreConfigParam.class);
//                List<Category> categories = categoryService.listByShopId(Constant.PLATFORM_SHOP_ID);
//                Map<Long, Double> categoryMap = CategoryScale.getScaleByCategory(categories,scoreParam,1);
//                //计算可以扣除的用户积分
//                double score = Arith.mul(Arith.div(orderItem.getActualTotal(), 100),categoryMap.get(product.getCategoryId()));
//                //TODO 根据现在等级计算积分有问题。
//                score = Arith.mul(score ,nowLevel.getRateScore());
//                receiptScore = Math.min((int)score,receiptScore);
//            }
//            if(receiptScore > 0) {
    }
}
